package com.mntp;

import com.mntp.handler.client.ClientInboundHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldPrepender;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

@Slf4j
public class NettyClient {
    public static void main(String[] args) {
        NettyClient client = new NettyClient();
        client.connect("127.0.0.1", 9999);
    }

    private void connect(String host, int port) {
        //准备客户端需要的 线程池
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventLoopGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        protected void initChannel(SocketChannel channel) throws Exception {
                            ChannelPipeline pipeline = channel.pipeline();
                            //固定长度字段保存消息长度，和服务端解码的字段长度设置保持一致
                            pipeline.addLast(new LengthFieldPrepender(4));
                            pipeline.addLast(new ClientInboundHandler());

                        }
                    });
            //连接服务器
            ChannelFuture future = bootstrap.connect(host, port).sync();
            //可以给服务器发送的数据
            Channel channel = future.channel();
            //channel.writeAndFlush("hello world");
            ByteBuf buffer = channel.alloc().buffer();


            buffer.writeBytes("hello netty server, i am netty client! \n ".getBytes(StandardCharsets.UTF_8));
            channel.writeAndFlush(buffer);
            // 等待连接关闭（优雅释放资源）
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            log.info("-----------客户端异常了。。。。Client connection interrupted", e);
            throw new RuntimeException(e);
        } finally {
            eventLoopGroup.shutdownGracefully();
        }
    }
}
